//
//  541. 反转字符串II.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/11.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation

class Solution541 {
    // 整个思路
    func reverseStr(_ s: String, _ k: Int) -> String {
        var cChars: [Character] = Array(s)
        for i in stride(from: 0, to: cChars.count - 1, by: 2 * k){
            // end 是关键
            let end = min(i + k - 1, cChars.count - 1)
            reversRange(&cChars, start: i, end: end)
        }
        return cChars.map { String($0) }.joined()
    }
    
    func reversRange(_ cChars:inout [Character], start: Int, end: Int) {
        var left = start
        var right = end
        while left < right {
            let tmp = cChars[left]
            cChars[left] = cChars[right]
            cChars[right] = tmp
            left += 1
            right -= 1
        }
    }
    static func test() {
        let s = "abcdefg"
        let k = 8
        let solution = Solution541()
        let result = solution.reverseStr(s, k)
        print(result)
    }
}
